package com.example.qxfw.dataBaseManager.nyzjk.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.ny.BadCondition;
import com.example.qxfw.common.entity.ny.CropGrowdateIndexlib;
import com.example.qxfw.common.entity.ny.Goodcondition;
import com.example.qxfw.common.entity.ny.StationInfo;
import com.example.qxfw.dataBaseManager.dto.CropGrowdateIndexlibDto;
import com.example.qxfw.dataBaseManager.nyzjk.service.NyfwzdkService;
import com.example.qxfw.dataBaseManager.nyzjk.service.TjszService;
import com.example.qxfw.dataBaseManager.nyzjk.service.ZwstqkService;
import com.example.qxfw.dataBaseManager.vo.StationVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/************************************
 *
 * @author : HuangDeYin Jolly
 * @since : JDK 11
 * @Date : 2023/7/6  星期四   14:59
 * @description : 此类用来
 ***************************************/
@Slf4j
@Api(tags = "数据库管理-农业专家库-作物生育期库")
@RestController
@CrossOrigin
@RequestMapping("/ZwstqkController")
public class ZwstqkController {

    @Autowired
    private ZwstqkService zwstqkService;

    @Autowired
    private TjszService tjszService;

    @Autowired
    private NyfwzdkService nyfwzdkService;

    @ApiOperation("作物生育期初始化列表")
    @GetMapping("selectOrderByCropName")
    public SysResult SelectOrderByCropName() {
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectOrderByCropName();
        return SysResult.success(cropGrowdateIndexlibs);
    }

    @ApiOperation("作物名称下拉框列表")
    @GetMapping("gropNameList")
    public SysResult cropNameList() {
        Set<String> cropNameList = new HashSet<>();
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectOrderByCropName();
        for (CropGrowdateIndexlib cropGrowdateIndexlib : cropGrowdateIndexlibs) {
            cropNameList.add(cropGrowdateIndexlib.getCropname());
        }
        return SysResult.success(cropNameList);
    }

    @ApiOperation("作物品种下拉框列表")
    @GetMapping("gropVarietyList")
    public SysResult gropVarietyList(String cropName) {
        Set<String> cropVarietyList = new HashSet<>();
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectByCropName(cropName);
        for (CropGrowdateIndexlib cropGrowdateIndexlib : cropGrowdateIndexlibs) {
            cropVarietyList.add(cropGrowdateIndexlib.getType());
        }
        return SysResult.success(cropVarietyList);
    }

    @ApiOperation("作物发育期下拉框列表")
    @GetMapping("growDateNameList")
    public SysResult cropVarietyList(String cropName) {
        Set<String> growDateNameList = new HashSet<>();
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectByCropName(cropName);
        for (CropGrowdateIndexlib cropGrowdateIndexlib : cropGrowdateIndexlibs) {
            growDateNameList.add(cropGrowdateIndexlib.getGrowdatename());
        }
        return SysResult.success(growDateNameList);
    }

    @ApiOperation("根据作物名称查询")
    @GetMapping("selectByCropName")
    public SysResult selectByCropName(String field, String cropName) {
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectColumn(field, cropName);
        return SysResult.success(cropGrowdateIndexlibs);
    }

    @ApiOperation("有利条件编辑中列表")
    @GetMapping("goodConditionList")
    public SysResult goodConditionList(Long indexId) {
        List<Goodcondition> goodConditionList = this.tjszService.selectGoodCondition(indexId);
        return SysResult.success(goodConditionList);
    }

    @ApiOperation("有利条件编辑中添加")
    @PostMapping("saveGoodCondition")
    public SysResult saveGoodCondition(@RequestBody Goodcondition goodcondition) {
        List<Goodcondition> goodConditionList = this.tjszService.selectGoodCondition(goodcondition.getIndexid());
        if (goodConditionList.size() > 0) {
            return SysResult.fail("只允许存在一条有利条件");
        }else {
            Integer result = this.tjszService.saveGoodCondition(goodcondition);
            if (result > 0) {
                return SysResult.success("添加成功");
            } else {
                return SysResult.fail("添加失败");
            }
        }
    }

    @ApiOperation("有利条件编辑中删除")
    @GetMapping("deleteGoodCondition")
    public SysResult deleteGoodCondition(Long indexId) {
        Integer result = this.tjszService.deleteGoodConditionByIndexId(indexId);
        if (result > 0) {
            return SysResult.success("删除成功");
        } else {
            return SysResult.fail("删除失败");
        }
    }

    @ApiOperation("有利条件编辑中修改")
    @PostMapping("updateGoodCondition")
    public SysResult updateGoodCondition(@RequestBody Goodcondition goodcondition) {
        Integer result = this.tjszService.updateGoodCondition(goodcondition);
        if (result > 0) {
            return SysResult.success("修改成功");
        } else {
            return SysResult.fail("修改失败");
        }
    }


    @ApiOperation("不利条件编辑中列表")
    @GetMapping("badConditionList")
    public SysResult badConditionList(Long indexId) {
        List<BadCondition> badConditionList = this.tjszService.selectByIndexId(indexId);
        return SysResult.success(badConditionList);
    }


    @ApiOperation("不利条件编辑中添加")
    @PostMapping("saveBadCondition")
    public SysResult saveBadCondition(@RequestBody BadCondition badCondition) {
        Integer result = this.tjszService.saveBadCondition(badCondition);
        if (result > 0) {
            return SysResult.success("添加成功");
        } else {
            return SysResult.fail("该记录已经存在");
        }
    }

    @ApiOperation("不利条件编辑中删除")
    @GetMapping("deleteBadCondition")
    public SysResult deleteBadCondition(BadCondition badCondition) {
        Integer result = this.tjszService.deleteBadConditionByAll(badCondition);
        if (result > 0) {
            return SysResult.success("删除成功");
        } else {
            return SysResult.fail("删除失败");
        }
    }

    //todo 修改的逻辑有问题，
    // 1.因为主键太多，如何准确获取要修改的数据
    // 2.如何确保修改后的数据不会和已经存在的数据重复
    @ApiOperation("不利条件编辑中修改")
    @PostMapping("updateBadCondition")
    public SysResult updateBadCondition(@RequestBody BadCondition badCondition) {
        Integer result = this.tjszService.updateBadCondition(badCondition);
        if (result > 0) {
            return SysResult.success("修改成功");
        } else {
            return SysResult.fail("修改失败");
        }
    }

    @ApiOperation("选取站点")
    @GetMapping("selectStation")
    public SysResult selectStation() {
        List<StationInfo> stationInfoList = this.nyfwzdkService.getAllOrder();
        List<StationVo> stationVoList = new ArrayList<>();
        for (StationInfo stationInfo : stationInfoList) {
            StationVo stationVo = new StationVo();
            stationVo.setStationid(stationInfo.getStationid());
            stationVo.setStationname(stationInfo.getStationname());
            stationVo.setStationtype(stationInfo.getStationtype());
            stationVo.setLon(stationInfo.getLon());
            stationVo.setLat(stationInfo.getLat());
            stationVo.setAlti(stationInfo.getAlti());
            stationVo.setMaincrop(stationInfo.getMaincrop());
            stationVo.setBasicsituation(stationInfo.getBasicsituation());
            stationVoList.add(stationVo);
        }
        return SysResult.success(stationVoList);
    }

    /*
    *这里的统计可以看成多条件查询
    *  */
    @ApiOperation("统计")
    @GetMapping("selectQuery")
    public SysResult selectQuery(CropGrowdateIndexlib cropGrowdateIndexlib) {
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectQuery(cropGrowdateIndexlib);
        return SysResult.success(cropGrowdateIndexlibs);
    }

    /*
    * 该接口暂时用不上，忽略
    * */
    @ApiIgnore
    @ApiOperation("查询指标编号")
    @GetMapping("getIndexId")
    public SysResult getIndexId() {
        List<CropGrowdateIndexlib> indexlibList = this.zwstqkService.getIndexId();
        return SysResult.success(indexlibList);
    }

    @ApiOperation("添加")
    @PostMapping("saveCropGrow")
    public SysResult saveCropGrow(@RequestBody CropGrowdateIndexlib cropGrowdateIndexlib) {
        List<CropGrowdateIndexlib> cropGrowdateIndexlibs = this.zwstqkService.selectQuery(cropGrowdateIndexlib);
        if (cropGrowdateIndexlibs.size() > 0) {
            return SysResult.fail("存在相同记录");
        } else {
            Integer integer = this.zwstqkService.saveCropGrowDateIndexLib(cropGrowdateIndexlib);
            if (integer > 0) {
                return SysResult.success("添加成功");
            } else {
                return SysResult.fail("添加失败");
            }
        }
    }

    @ApiOperation("更新")
    @PostMapping("updateCropGrow")
    public SysResult updateCropGrow(@RequestBody CropGrowdateIndexlib cropGrowdateIndexlib) {
        Integer integer = this.zwstqkService.updateCropGrowDateIndexLib(cropGrowdateIndexlib);
        if (integer>0){
            return SysResult.success("更新成功");
        }else {
            return SysResult.fail("更新失败");
        }
    }


    //todo 因为删除要删三类记录
    /*
    * 1.删除三个表
    * 2.删除三个表都要判断是否为空
    *
    * */
    @ApiOperation("删除")
    @PostMapping("deleteCropGrow")
    public SysResult deleteCropGrow(String indexId){
        Integer integer = this.zwstqkService.deleteCropGrowFateIndexLib(indexId);

        Integer deleteGoodConditionresult = this.tjszService.deleteGoodConditionByIndexId(Long.valueOf(indexId));

        Integer deleteBadConditionresult = this.tjszService.deleteBadConditionByIndexId(Long.valueOf(indexId));

        if (integer>0 && deleteGoodConditionresult>0 && deleteBadConditionresult>0){
            return SysResult.success("删除成功");
        }else {
            return SysResult.fail("删除失败");
        }
    }

    @ApiOperation("批量导入")
    @PostMapping("/importCropGrowdateIndexlib")
    @ResponseBody
    public SysResult importCropGrowdateIndexlib(MultipartFile file) {
        if (file.isEmpty()) {
            return returnInformation("作物生育期信息", null);
        }

        List<CropGrowdateIndexlibDto> cropGrowdateIndexlibDtoList = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();

            Workbook workbook = null;
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".xls".equals(fileType)) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (".xlsx".equals(fileType)) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                return returnInformation("作物生育期信息", null);
            }
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                for (Row row : sheet) {
                    if (row.getRowNum() > 0) { // 假设第一行为标题行
                        CropGrowdateIndexlibDto cropGrowdateIndexlibDto = new CropGrowdateIndexlibDto();
                        for (Cell cell : row) {
                            int columnIndex = cell.getColumnIndex();
                            switch (columnIndex) {
                                case 0: cropGrowdateIndexlibDto.setIndexid((int) cell.getNumericCellValue()); break;
                                case 1: cropGrowdateIndexlibDto.setCropname(cell.getStringCellValue()); break;
                                case 2: cropGrowdateIndexlibDto.setType(cell.getStringCellValue()); break;
                                case 3: cropGrowdateIndexlibDto.setGrowdatename(cell.getStringCellValue());; break;
                                case 4: cropGrowdateIndexlibDto.setGrowdatestarttime(cell.getDateCellValue()); break;
                                case 5: cropGrowdateIndexlibDto.setGrowdateendtime(cell.getDateCellValue()); break;
                                case 6: cropGrowdateIndexlibDto.setDefendmeasure(cell.getStringCellValue()); break;
                                case 7: cropGrowdateIndexlibDto.setJoinstation(cell.getStringCellValue()); break;
                                case 8: cropGrowdateIndexlibDto.setAgriaction(cell.getStringCellValue()); break;

                                default: break;
                            }

                        }
                        cropGrowdateIndexlibDtoList.add(cropGrowdateIndexlibDto);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        Integer importcropGrowdateIndexlibDto = this.zwstqkService.importcropGrowdateIndexlibDto(cropGrowdateIndexlibDtoList);
        return returnInformation("导入作物生育期信息", importcropGrowdateIndexlibDto);
    }

    public SysResult returnInformation(String info, Integer result) {
        if (result < 0) {
            return SysResult.fail(info + "失败");
        } else {
            return SysResult.success(result);
        }
    }
}
